layui.use(['form', 'layer', 'laydate'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        laydate = layui.laydate,
        $ = layui.jquery;

    laydate.render({
        elem: '#payDate',
        format: "yyyy-MM-dd"
    });

    $("#checkAmountDiscounts").click(function (){
        var amountPaid = new Decimal($("input[name='amountPaid']").val()||0);
        var oldAmountDiscounts = new Decimal($("input[name='amountDiscounts']").val()||0);
        if(amountPaid > 0 && oldAmountDiscounts <= 0 ){
            var oldAmountPaid = new Decimal($("input[name='oldAmountPaid']").val()); // 修改之前的支付金额
            var amountNotPaid = new Decimal($("input[name='amountNotPaid']").val());
            // 优惠金额 = 未付金额 + 修改之前的支付金额 - 修改之后的支付金额
            var amountDiscounts = amountNotPaid.plus(oldAmountPaid).minus(amountPaid);
            if(amountDiscounts > 0){
                layui.jquery("#amountDiscounts").val(amountDiscounts);
            }
        } else {
            layui.jquery("#amountDiscounts").val(0);
        }
    });

    form.on("submit(addOrUpdateSaleListPayment)", function (data) {
        var index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        //弹出loading
        var url=ctx + "/saleListPayment/save";
        if($("input[name='id']").val()){
            url=ctx + "/saleListPayment/update";
        }
        $.post(url, data.field, function (res) {
            if (res.code == 200) {
                setTimeout(function () {
                    top.layer.close(index);
                    top.layer.msg("操作成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                }, 500);
            } else {
                layer.msg(
                    res.message, {
                        icon: 5
                    }
                );
            }
        });
        return false;
    });

    $("#closeDlg").click(function (){
        // iframe 页面关闭 添加parent
        parent.layer.closeAll();
    })
});
